package com.ytjj.qmyx.supplychain.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;

import java.util.HashMap;

@Slf4j
public class DingDingWebHookUtil {

    //https://oapi.dingtalk.com/robot/send?access_token=283f14ad624e80820f3044422dff6d6969cc2bd0274894ea25675263062bca7e
    //运费异常机器人
    //关键字：运费
    private final static String access_token = "283f14ad624e80820f3044422dff6d6969cc2bd0274894ea25675263062bca7e";//
    //请求地址以及access_token
    //https://oapi.dingtalk.com/robot/send?access_token=67a026cf07bcbed8e5b0b933d33aef8d8711a6f3a4c1f88018f140f0f34de4d9
    //关键字：跨境
//    private final static String access_token = "67a026cf07bcbed8e5b0b933d33aef8d8711a6f3a4c1f88018f140f0f34de4d9";

    public static Boolean pushInfoToDingding(String textMsg, String privateAccessToken) {
        if (StringUtils.isEmpty(privateAccessToken)) {
            privateAccessToken = access_token;
        }

        HashMap<String, Object> resultMap = new HashMap<>(8);
        resultMap.put("msgtype", "text");

        HashMap<String, String> textItems = new HashMap<>(8);
        textItems.put("content", textMsg);
        resultMap.put("text", textItems);

        HashMap<String, Object> atItems = new HashMap<>(8);
        atItems.put("atMobiles", null);
        atItems.put("isAtAll", false);
        resultMap.put("at", atItems);


        String dingURL = "https://oapi.dingtalk.com/robot/send?access_token=" + privateAccessToken;
        try {
            HttpClient httpClient = HttpClients.createDefault();
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(resultMap), "utf-8");

            HttpPost httpPost = createConnectivity(dingURL);
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
                log.info("执行结果：{}" , result);
            }
            return Boolean.TRUE;
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }

    static HttpPost createConnectivity(String restUrl) {
        HttpPost post = new HttpPost(restUrl);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Accept", "application/json");
        post.setHeader("X-Stream", "true");
        return post;
    }

}